package com.primefaces.www.dao;

import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.primefaces.www.dto.Image;

@Component
public class ImagesDAO extends BaseDAO {
	private static final Logger logger = LoggerFactory
			.getLogger(ImagesDAO.class);

	@Transactional
	public List<Image> getAllImages(String galleryId){
		logger.info("getAllImages called");
		List<Image> images = null;
		
		Cache cache=cacheManager.getCache("images");
		if(cache != null){
			Element e = cache.get(galleryId);
			if(e != null){
				images = (List<Image>)e.getObjectValue();
			}
		}
		if(images == null){ 
			images = (List<Image>) getCurrentSession().createQuery("from Image").list();
			if(images != null){
				saveImagesCache(images,galleryId);
			}
		}
		return images;	
	}

	public void saveImagesCache(List<Image> images, String galleryId){
		Cache cache = cacheManager.getCache("images");
		logger.info("############## cache:"+ cache +"#######");
		cache.put(new Element(galleryId, images));
		
	}
}
